import express from 'express';
import cors from 'cors';
import fs from 'fs';
// 引入数据库连接文件
import mysql2 from 'mysql2';
import jsyaml from 'js-yaml';

import admin from './router/admin.js'
import {
    tinypng
} from './router/tools/tinypng.js'

import {
  upload,
  merge,
  editVideo,
  downloadFile
} from './router/tools/upload.js'


const yaml = fs.readFileSync('./db.config.yaml', 'utf8');
const config = jsyaml.load(yaml);
// 连接数据库
const sql = await mysql2.createConnection({
  ...config.db
});

console.log('sql----------------:\n')
// 使用promise模式
const promiseCon = sql.promise();
const app = express();

app.use(cors());
app.use(express.json());

// app.use(admin)
app.use(tinypng)
app.use(upload)
app.use(merge)
app.use(editVideo)
app.use(downloadFile)
app.use('/admin',admin)


app.post('/getUserinfo', async (req, res) => {
  const { username, password } = req.body;
  const [user] = await promiseCon.query('select * from user_list where name=?', [username])
  console.log('====>iii', user);
  if (user.length > 0) {
    // 登录成功
    res.send({
      msg: '登录成功',
      code: 200,
      data: {
        token: new Date().getTime(),
        password,
        username: user[0].name
      }
    })
  } else {
    // 注册用户
    await promiseCon.query('insert into user_list (name,create_time) values (?,?)', [username, new Date()])
    res.send({
      msg: '注册成功',
      code: 200,
      data: {
        token: new Date().getTime(),
        password,
        username
      }
    })
  }
})

app.get('/login', (req, res) => {
  console.log('GET re0000quest received');
  res.send({
    msg: 'ok',
    code: 200,
    data: {
      token: new Date().getTime()
    }
  });
});
// 连接数据库

const port = process.env.PORT || 8080;
app.set('host', '192.168.52.13')
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});